package com.hk.yingmi;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.hk.commons.StringHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hk.Mgr.web.message.StatusCode;
import com.hk.Mgr.web.message.order.FundInfoReq;
import com.hk.Mgr.web.message.order.FundInfoRes;
//import com.hk.Mgr.web.message.order.FundInfo_YimiDBHelper;
import com.hk.base.ResponseBase;
import com.hk.commons.HqlFilter;
import com.hk.commons.JsonUtils;
import com.hk.commons.entity.FundInfo_Yimi;
import com.hk.commons.entity.product.Company;
import com.hk.commons.entity.yingmi.FundNav;
import com.hk.commons.utils.yingmi.YingmiApiUtils;
import com.hk.commons.vo.FundInfoVoNav;
import com.hk.service.IFundInfo_Yimi;
import com.hk.service.IFundNav;
import com.hk.service.product.ICompany;

@Controller
public class FundInfoCtrl {

	@Autowired
	private IFundInfo_Yimi fundInfoService;
	@Autowired
	public YingmiApiUtils utils;

	@Autowired
	public IFundNav fundNavService;

	@Autowired
	public ICompany companyService;

	private Logger logger = LoggerFactory.getLogger(FundInfoCtrl.class);

	@ResponseBody
	@RequestMapping(value = "/fundInfoList", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
	public String fundInfoList(@RequestBody FundInfoReq req) {
		logger.info("seacher fundType:{} , curPage:{} , pageSize:{}",
				req.getFundType(), req.getCurPage(), req.getPageSize());

		String fundType = req.getFundType();
		StringBuffer buf = new StringBuffer();
		String hql = "Select new com.hk.commons.vo.FundInfoVoNav(fi.fundFullName,fn.navDate,fn.fundCode , fn.nav , fn.oneWeekReturn , fn.dayReturn , fn.unitYield , fn.yearlyRoe , fi.fundType)from FundInfo_Yimi fi , FundNav fn where fi.fundType = "
				+ fundType + " and fi.fundCode = fn.fundCode and fi.onSale = 1";
		/**
		 * 排序规则: 1 nav asc 2 nav desc 3 dayReturn asc 4 dayReturn desc 5
		 * unitYield(货币型基金) asc 6 unitYield(货币型基金) desc 7 yearlyRoe(货币型基金) 8
		 * yearlyRoe(货币型基金)
		 */
		buf.append(hql);
		if (req.getOrderByType() != null) {
			switch (req.getOrderByType()) {
			case "1":
				buf.append(" order by  nav asc");
				break;
			case "2":
				buf.append(" order by nav desc ");
				break;
			case "3":
				buf.append(" order by dayReturn asc");
				break;
			case "4":
				buf.append(" order by dayReturn desc");
				break;
			case "5":
				buf.append(" order by unitYield asc");
				break;
			case "6":
				buf.append(" order by unitYield desc");
				break;
			case "7":
				buf.append(" order by yearlyRoe asc");
				break;
			case "8":
				buf.append(" order by yearlyRoe desc");
				break;
			default:
				buf.append("");
				break;

			}
		}

		int firstResult = (req.getCurPage() - 1) * req.getPageSize();
		int maxSize = req.getPageSize();

		@SuppressWarnings("unchecked")
		List<FundInfoVoNav> list = fundNavService.executeListHql(
				String.valueOf(buf), firstResult, maxSize);

		return JsonUtils.toJson(list);

	}

	@ResponseBody
	@RequestMapping(value = "/getFuu", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
	public String fundInfoList(@RequestParam String fundType) {
		StringBuffer buf = new StringBuffer();
		String hql = "Select new com.hk.commons.vo.FundInfoVoNav(fi.fundFullName,fn.navDate,fn.fundCode , fn.nav , fn.oneWeekReturn , fn.dayReturn , fn.unitYield , fn.yearlyRoe , fi.fundType)from FundInfo_Yimi fi , FundNav fn where fi.fundType = "
				+ fundType + " and fi.fundCode = fn.fundCode and fi.onSale = 1";
		/**
		 * 排序规则: 1 nav asc 2 nav desc 3 dayReturn asc 4 dayReturn desc 5
		 * unitYield(货币型基金) asc 6 unitYield(货币型基金) desc 7 yearlyRoe(货币型基金) 8
		 * yearlyRoe(货币型基金)
		 */
		buf.append(hql);

		@SuppressWarnings("unchecked")
		List<FundInfoVoNav> list = fundNavService.executeListHql(
				String.valueOf(buf), 0, 10);

		return JsonUtils.toJson(list);

	}

	/*
	 * @ResponseBody
	 * 
	 * @RequestMapping(value = "/fundInfo", method = RequestMethod.POST)
	 */
	public ResponseBase<String> getFundInfo(@RequestBody FundInfoReq req) {
		ResponseBase<String> resp = new ResponseBase<String>();

		logger.info("seacher fundType:{} , curPage:{} , pageSize:{}",
				req.getFundType(), req.getCurPage(), req.getPageSize());

		String fundInfoRes = getFundInfoById(req.getFundCode());
		if (fundInfoRes != null) {
			resp.setResultCode(StatusCode.SUCCESS.key());
			resp.setResult(fundInfoRes);
			resp.setSize(1);
		} else {
			resp.setMsg("获取基金信息失败");
			resp.setResultCode(StatusCode.EXCEPTION.key());
		}

		return resp;
	}

	/*
	 * @ResponseBody
	 * 
	 * @RequestMapping(value = "/updateAllFundInfo", method =
	 * RequestMethod.POST)
	 */

	/**
	 * 获取基金的基本信息
	 * 
	 * @param req
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/fundMessageList", method = RequestMethod.POST)
	public ResponseBase<List<FundInfoRes>> fundMessageList(
			@RequestBody FundInfoReq req) {
		ResponseBase<List<FundInfoRes>> resp = new ResponseBase<>();
		List<FundInfoRes> fundInfoResList = new ArrayList<>();
		HqlFilter hqlFilter = new HqlFilter();
		if (!req.getOnSale().equals("")) {
			int onSale = Integer.parseInt(req.getOnSale());
			hqlFilter.addEQFilter("onSale", onSale);// 过滤只在
		}
		hqlFilter.addEQFilter("fundType", req.getFundType());
		if (StringHelper.isNotEmpty(req.getFundFullName())) {
			hqlFilter.addLKFilter("fundFullName", req.getFundFullName());
		}

		if (StringHelper.isNotEmpty(req.getFundCode())) {
			hqlFilter.addEQFilter("fundCode", req.getFundCode());
		}
		hqlFilter.addSort("fundCode");
		hqlFilter.addOrder("desc");

		List<FundInfo_Yimi> list = fundInfoService.findByFilter(hqlFilter,
				req.getCurPage(), req.getPageSize());

		for (FundInfo_Yimi fundInfo : list) {
			FundInfoRes fundInfoRes = new FundInfoRes();
			// 设置基金信息
			fundInfoRes.setFundInfo(fundInfo);

			// 发行公司信息
			if (fundInfo.getCompanyId() != null) {
				Company company = companyService.findById(fundInfo
						.getCompanyId());
				fundInfoRes.setCompany(company);
			}

			fundInfoResList.add(fundInfoRes);
		}

		Long total = fundInfoService.countByFilter(hqlFilter);

		resp.setSize(total);
		resp.setResult(fundInfoResList);
		resp.setResultCode(200);
		return resp;

	}

	public void updateAllFundInfo() {
		HqlFilter hqlFilter = new HqlFilter();
		List<FundNav> list = fundNavService.findByFilter(hqlFilter, 0, 999999);
		for (FundNav fi : list) {
			String fundCode = fi.getFundCode();
			getFundInfoById(fundCode);
		}
	}

	private String getFundInfoById(String fundCode) {
		String resultStr = null;
		String url = "/product/getFundInfo";
		Map<String, String> params = new HashMap<>();
		params.put("fundCode", fundCode);
		resultStr = utils.get(url, params);

		/*
		 * FundInfo_YimiDBHelper fundInfo_YimiHelper = null; if (resultStr !=
		 * null) { fundInfo_YimiHelper = new FundInfo_YimiDBHelper();
		 * 
		 * try { fundInfo_YimiHelper = JsonUtils.toBean(resultStr,
		 * FundInfo_YimiDBHelper.class);
		 * 
		 * if (fundInfo_YimiHelper != null) { FundInfo_Yimi fundInfo_Yimi =
		 * getFromYimiHelper(fundInfo_YimiHelper); }
		 * 
		 * } catch (Exception e) { logger.error("类型转换错误， 无法查到基金信息 fundCode = " +
		 * fundCode); } // resultStr = JsonUtils.toJson(fundInfo_YimiHelper); }
		 */
		return resultStr;
	}

	/*
	 * private FundInfo_Yimi getFromYimiHelper( FundInfo_YimiDBHelper
	 * fundInfo_YimiHelper) { FundInfo_Yimi fundInfo_Yimi = new FundInfo_Yimi();
	 * 
	 * fundInfo_Yimi.setFundCode(fundInfo_YimiHelper.getFundCode());
	 * fundInfo_Yimi.setFundFullName(fundInfo_YimiHelper.getFundFullName());
	 * fundInfo_Yimi.setFundName(fundInfo_YimiHelper.getFundName());
	 * fundInfo_Yimi.setFundType(fundInfo_YimiHelper.getFundType());
	 * fundInfo_Yimi.setRiskLevel(fundInfo_YimiHelper.getRiskLevel());
	 * fundInfo_Yimi.setConfirmPace(fundInfo_YimiHelper.getConfirmPace());
	 * fundInfo_Yimi.setRefundPace(fundInfo_YimiHelper.getRefundPace());
	 * fundInfo_Yimi.setDefaultDividendMethod(fundInfo_YimiHelper
	 * .getDefaultDividendMethod());
	 * fundInfo_Yimi.setAllowUpdateDividendMethod(fundInfo_YimiHelper
	 * .getAllowUpdateDividendMethod());
	 * 
	 * fundInfo_Yimi.setCurrency(fundInfo_YimiHelper.getCurrency());
	 * fundInfo_Yimi.setOnSale(fundInfo_YimiHelper.getOnSale()); if
	 * (fundInfo_YimiHelper.getShareType() != null) {
	 * fundInfo_Yimi.setShareTypeJArray(fundInfo_YimiHelper.getShareType()
	 * .toString()); } fundInfo_Yimi.setSupportPeriodic(fundInfo_YimiHelper
	 * .getSupportPeriodic());
	 * fundInfo_Yimi.setSupportAllot(fundInfo_YimiHelper.getSupportAllot());
	 * fundInfo_Yimi.setSupportSubscribe(fundInfo_YimiHelper
	 * .getSupportSubscribe());
	 * fundInfo_Yimi.setSupportBuy(fundInfo_YimiHelper.getSupportBuy());
	 * fundInfo_Yimi
	 * .setSupportConvert(fundInfo_YimiHelper.getSupportConvert());
	 * fundInfo_Yimi.setSaleRate(fundInfo_YimiHelper.getSaleRate());
	 * fundInfo_Yimi.setManagerRate(fundInfo_YimiHelper.getManagerRate());
	 * fundInfo_Yimi.setTrusteeRate(fundInfo_YimiHelper.getTrusteeRate()); if
	 * (fundInfo_YimiHelper.getSubscribeRate() != null) {
	 * fundInfo_Yimi.setSubscribeRateJArray(fundInfo_YimiHelper
	 * .getSubscribeRate().toString()); } if (fundInfo_YimiHelper.getAllotRate()
	 * != null) {
	 * fundInfo_Yimi.setAllotRateJArray(fundInfo_YimiHelper.getAllotRate()
	 * .toString()); } if (fundInfo_YimiHelper.getRedeemRate() != null) {
	 * fundInfo_Yimi.setRedeemRateJArray(fundInfo_YimiHelper
	 * .getRedeemRate().toString()); }
	 * 
	 * fundInfo_Yimi.setMinIndividualSubscribeAmount(fundInfo_YimiHelper
	 * .getMinIndividualSubscribeAmount());
	 * fundInfo_Yimi.setMinIndividualAppendSubscribeAmount(fundInfo_YimiHelper
	 * .getMinIndividualAppendSubscribeAmount());
	 * fundInfo_Yimi.setMaxIndividualSubscribeAmount(fundInfo_YimiHelper
	 * .getMaxIndividualSubscribeAmount());
	 * fundInfo_Yimi.setMinIndividualAllotAmount(fundInfo_YimiHelper
	 * .getMinIndividualAllotAmount());
	 * fundInfo_Yimi.setMinIndividualAppendAllotAmount(fundInfo_YimiHelper
	 * .getMinIndividualAppendAllotAmount());
	 * fundInfo_Yimi.setMaxIndividualAllotAmount(fundInfo_YimiHelper
	 * .getMaxIndividualAllotAmount());
	 * fundInfo_Yimi.setMinIndividualPeriodicAmount(fundInfo_YimiHelper
	 * .getMinIndividualPeriodicAmount());
	 * fundInfo_Yimi.setMinIndividualHoldVol(fundInfo_YimiHelper
	 * .getMinIndividualHoldVol());
	 * fundInfo_Yimi.setMinIndividualRedeemVol(fundInfo_YimiHelper
	 * .getMinIndividualRedeemVol());
	 * fundInfo_Yimi.setMinIndividualConvertVol(fundInfo_YimiHelper
	 * .getMinIndividualConvertVol());
	 * fundInfo_Yimi.setSetupDate(fundInfo_YimiHelper.getSetupDate());
	 * 
	 * if (fundInfo_YimiHelper.getFundCorp() != null) {
	 * fundInfo_Yimi.setFundCorp(fundInfo_YimiHelper.getFundCorp() .toString());
	 * }
	 * 
	 * fundInfo_Yimi.setTrustee(fundInfo_YimiHelper.getTrustee()); if
	 * (fundInfo_YimiHelper.getFundManager() != null) {
	 * fundInfo_Yimi.setFundManagerJArray(fundInfo_YimiHelper
	 * .getFundManager().toString()); }
	 * 
	 * fundInfo_Yimi.setReportDate(fundInfo_YimiHelper.getReportDate());
	 * fundInfo_Yimi.setAssetAmount(fundInfo_YimiHelper.getAssetAmount());
	 * fundInfo_Yimi.setAssetVol(fundInfo_YimiHelper.getAssetVol());
	 * 
	 * if (fundInfo_YimiHelper.getStockPortfolio() != null) {
	 * fundInfo_Yimi.setStockPortfolioJArray(fundInfo_YimiHelper
	 * .getStockPortfolio().toString()); } if
	 * (fundInfo_YimiHelper.getIndustryPortfolio() != null) {
	 * fundInfo_Yimi.setIndustryPortfolioJArray(fundInfo_YimiHelper
	 * .getIndustryPortfolio().toString()); }
	 * 
	 * if (fundInfo_YimiHelper.getAssetPortfolio() != null) {
	 * fundInfo_Yimi.setAssetPortfolioJArray(fundInfo_YimiHelper
	 * .getAssetPortfolio().toString()); } fundInfoService.merge(fundInfo_Yimi);
	 * 
	 * return fundInfo_Yimi; }
	 */
}
